/*
    文件内容: Connection类,处理TcpServer中绑定和listen的相关操作
    文件名: Connection.h
    作者: 中国好青年(码农论坛)
    时间: 2024/9/8
*/

#pragma once
#include "EventLoop.h"
#include "InetAddress.h"
#include "Socket.h"
#include "Buffer.h"
#include <memory>
#include <atomic>
#include "util.h"
#include "TimeStamp.h"

class Connection;
class Channel;
class EventLoop;
using spConnection = std::shared_ptr<Connection>;

/*
    类名: Connection
    作用: 封装Connection相关操作类
*/
class Connection : public std::enable_shared_from_this<Connection>
{
private:
    EventLoop *loop_;
    std::unique_ptr<Socket>  clientsock_;
    std::unique_ptr<Channel> clientchan_;
    Buffer    inputbuffer_;
    Buffer    outputbuffer_;
    TimeStamp lasttime_;
    std::atomic<bool> disconnectFlag_;
    std::function<void(spConnection)> closeconncallback_;
    std::function<void(spConnection)> errorconncallback_;
    std::function<void(spConnection, std::string&)> onmessagecallback_;
    std::function<void(spConnection)> sendcomletecallback_;
    
public:
    /* 构造函数 和 析构函数 */
    Connection(EventLoop* loop, std::unique_ptr<Socket> servsock);
    ~Connection();

    int fd()const;
    std::string ip()const;
    uint16_t port()const;
    
    void closeCallback();
    void errorCallback();
    void wirteCallback(); 
    void onMessage();
    void sendOnMessage(std::shared_ptr<std::string> message);
    void send(const char* data, size_t size);
    bool isTimeout(time_t now, int val);

    void setcloseconncallback(std::function<void(spConnection)> closeconncallback);
    void seterrorconncallback(std::function<void(spConnection)> errorconncallback);
    void setonmessagecallback(std::function<void(spConnection, std::string&)> onmessagecallback);
    void setwritecallback(std::function<void(spConnection, std::string)> onmessagecallback);
    void setsendCompletecallback(std::function<void(spConnection)> sendcomletecallback);
};